package com.example.shopping.service;

import com.example.shopping.dto.CartItem;
import com.example.shopping.entity.Cart;
import com.example.shopping.entity.Goods;
import com.example.shopping.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsService goodsService;


    public List<CartItem> getCar(Integer userid) {
        return cartMapper.findCarByUserId(userid);
    }

    public Double getTotalPrice(Integer id) {
        List<CartItem> car = this.getCar(id);
        Double totalPrice = 0.0;
        //遍历计算价格
        for (CartItem carItem : car) {
            totalPrice += carItem.getGoodprice() * carItem.getNum();
        }
        return totalPrice;
    }

    public boolean addCar(int userid, int goodid, int num, String option) {
        //1.1. 判断购物车是否有该商品
        Cart cart = cartMapper.findCarByGoodId(userid, goodid);
        Goods goods = goodsService.findById(goodid);
        if(goods==null){
            return false;
        }
        Integer stock = goods.getStock();
        if (cart != null) {

            if (cart.getNum() + num > stock) {
                return false;
            }
            if ("add".equals(option)) {
                cart.setNum(cart.getNum() + num);

            } else if ("update".equals(option)) {
                cart.setNum(num);
            }
            cartMapper.updateCar(cart);
            return true;

        }
        if (num > stock) {
            return false;
        }
        cart = new Cart();
        cart.setUserid(userid);
        cart.setGoodid(goodid);
        cart.setNum(num);
        return cartMapper.insert(cart) > 0;

    }


    public boolean deleteById(Integer itemId) {
        return cartMapper.deleteById(itemId) > 0;
    }

    public boolean updateQuantity(Long itemId, Integer quantity) {

        return cartMapper.updateCarQuantity(itemId, quantity) > 0;

    }
}
